<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 角色管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                        <el-select v-model="query.status" placeholder="状态" class="filter-item handle-select mr10">
                            <el-option key="0" label="全部" value=""></el-option>
                            <el-option key="1" label="启用" value="1"></el-option>
                            <el-option key="2" label="禁用" value="2"></el-option>
                        </el-select>
                        <el-input v-model="query.roleName" placeholder="角色名" class="filter-item handle-input mr10"></el-input>

                        <el-button type="primary" class="filter-item" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                        <el-button type="primary" class="filter-item" icon="el-icon-plus" @click="handleAdd">新增</el-button>

            </div>
            <el-table
                v-loading="loading"
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="roleName" label="角色名"></el-table-column>
                <el-table-column label="状态" align="center" >
                    <template slot-scope="scope">
                        <el-tag
                            :type="scope.row.status==='1'?'success':(scope.row.status==='0'?'danger':'')"
                        >{{scope.row.status | showStatus}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="orderNum" label="排序" ></el-table-column>
                <el-table-column prop="createTime" label="创建时间">
                    <template slot-scope="scope">
                        <span>{{ parseDateTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="220" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-user-solid"
                                @click="handleDataScopeEdit(scope.$index, scope.row)"
                        >数据权限</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.current"
                    :page-size="query.size"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="角色名">
                    <el-input v-model="form.roleName"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="form.status" placeholder="请选择">
                        <el-option
                                v-for="item in form.statusOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="权限">
                    <el-tree
                            :data="form.sysMenuAll"
                            show-checkbox
                            check-strictly
                            node-key="id"
                            ref="tree"
                            :default-checked-keys="form.checkedKeys"
                            :props="defaultProps">
                    </el-tree>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input v-model="form.orderNum"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="编辑" :visible.sync="editDataScopeVisible" width="50%">
            <el-form ref="form" :model="dataScopeForm" label-width="70px">
                <el-form-item label="角色名">
                    <el-input v-model="dataScopeForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="dataScopeForm.dataScope" placeholder="请选择">
                        <el-option label="所有数据权限" value="1"></el-option>
                        <el-option label="自定义数据权限" value="2"></el-option>
                        <el-option label="本部门数据权限" value="3"></el-option>
                        <el-option label="本部门及以下数据权限" value="4"></el-option>
                        <el-option label="本人" value="5"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门" v-if="dataScopeForm.dataScope == '2'">
                    <el-tree
                            :data="dataScopeForm.roleDeptAll"
                            show-checkbox
                            node-key="id"
                            ref="deptTree"
                            :default-checked-keys="dataScopeForm.checkedKeys"
                            :props="{children: 'children',label: 'name'}">
                    </el-tree>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDataScopeVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveDataScopeEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { allSysMenuByRoleList } from '../../api/sysMenu';
import { sysRolePage,saveSysRole,updateSysRole,delSysRole } from '../../api/sysRole';
import { sysRoleDeptList,updateSysRoleDept } from '../../api/sysRoleDept';

export default {
    name: 'sys-role-list',
    data() {
        return {
            // 遮罩层
            loading: true,
            query: {
                status: '',
                roleName: '',
                current: 1,
                size: 10
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            editDataScopeVisible: false,
            pageTotal: 0,
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            form: {
                roleName:"",
                status:"",
                orderNum:0,
                sysMenuAll:[],
                statusOptions: [{
                    value: '1',
                    label: '启用'
                }, {
                    value: '2',
                    label: '禁用'
                }]
            },
            dataScopeForm:{
                roleName:"",
                dataScope:"3",
                roleDeptAll:[],
                checkedKeys:[]
            },
            idx: -1,
            id: -1
        };
    },
    created() {
        this.defaultform = JSON.parse(JSON.stringify(this.form));
        this.getData();
    },
    destroyed() {
        this.defaultform = null;
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        getData() {
            this.loading = true;
            sysRolePage(this.query).then(res => {
                this.loading = false;
                this.tableData = res.data;
                this.pageTotal = res.count;
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'current', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    delSysRole(row.id).then(res => {
                        if (res.code == 0) {
                            this.editVisible = false;
                            this.$message.success(`删除成功`);
                            this.getData();
                        } else {
                            this.$message.error(res.msg);
                            return false;
                        }
                    });
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        handleAdd(){
            this.form = Object.assign({}, this.defaultform);
            allSysMenuByRoleList({}).then(res => {
                this.form.sysMenuAll = res.data;
                this.form.checkedKeys = res.menuIds;
            });
            this.editVisible = true;
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form.id = row.id;
            this.form.roleName = row.roleName;
            this.form.status = row.status;
            this.form.orderNum = row.orderNum;
            // :default-expanded-keys="[2, 3]"，默认打开
            // 整个menu，及当前用户所拥有的的权限
            allSysMenuByRoleList({roleId:row.id}).then(res => {
                this.form.sysMenuAll = res.data;
                this.form.checkedKeys = res.menuIds;
            });
            // console.log(this.form)
            this.editVisible = true;
        },
        handleDataScopeEdit(index, row) {
            this.dataScopeForm.id = row.id;
            this.dataScopeForm.roleName = row.roleName;
            this.dataScopeForm.dataScope = row.dataScope;
            sysRoleDeptList({roleId:row.id}).then(res => {
                this.dataScopeForm.roleDeptAll = res.sysDeptList;
                this.dataScopeForm.checkedKeys = res.checkDeptIdList;
            });
            this.editDataScopeVisible = true;
        },
        // 保存编辑
        saveEdit() {
            this.$refs['form'].validate((valid) => {
                if (!valid) {
                    console.log('error submit!!');
                    return false;
                }
                // tree的值获取
                let nodes = this.$refs.tree.getCheckedNodes();
                if (nodes == null || nodes <= 0) {
                    this.$message.error(`请选择权限`);
                    return false;
                }
                let menuIdArr = [];
                nodes.forEach(item => {
                    menuIdArr.push(item.id);
                })
                this.form.menuIds = menuIdArr.join(",");
                if (this.form.id) {
                    updateSysRole(this.form).then(res => {
                        if (res.code == 0) {
                            this.editVisible = false;
                            this.$message.success(`修改成功`);
                            this.getData();
                        } else {
                            this.$message.error(res.msg);
                            return false;
                        }
                    });
                } else {
                    saveSysRole(this.form).then(res => {
                        if (res.code == 0) {
                            this.editVisible = false;
                            this.$message.success(`保存成功`);
                            this.getData();
                        } else {
                            this.$message.error(res.msg);
                            return false;
                        }
                    });
                }
            });
        },
        // 保存权限
        saveDataScopeEdit() {
            // tree的值获取
            let dataScope = this.dataScopeForm.dataScope;
            let deptIds = "";
            if (dataScope == 2) {
                let nodes = this.$refs.deptTree.getCheckedNodes();
                if (nodes == null || nodes <= 0) {
                    this.$message.error(`请选择权限`);
                    return false;
                }
                let deptIdArr = [];
                nodes.forEach(item => {
                    deptIdArr.push(item.id);
                })
                deptIds = deptIdArr.join(",");
            }

            let data = {
                id:this.dataScopeForm.id,
                dataScope:dataScope,
                deptIds:deptIds
            };
            updateSysRoleDept(data).then(res => {
                if (res.code == 0) {
                    this.editDataScopeVisible = false;
                    this.$message.success(`修改成功`);
                    this.getData();
                } else {
                    this.$message.error(res.msg);
                    return false;
                }
            });
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'current', val);
            this.getData();
        }
    },
    filters:{
        showStatus(status){
            if (status == "1") {
                return "启用";
            } else if (status == "2") {
                return "禁用";
            } else {
                return "";
            }
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
